<template>
  <div>
    <el-dialog
      ref="refDlg"
      :title="formData.id ? '编辑' : '新增'"
      :visible.sync="dialogShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="800"
      @close="handleBack"
    >
      <div>
        <el-form ref="refForm" class="financeForm" :rules="formRules" :model="formData" size="mini" label-width="130px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="节点配置名称:" size="mini" prop="configName">
                <el-input v-model.trim="formData.configName" placeholder="请输入节点配置名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="对应流程:" size="mini" prop="belongProcess">
                <c-dict-select v-model="formData.belongProcess" dict-type-code="CORRESPONDING_PROCESS" placeholder="对应流程" style="width:100%" @change="changeProcess" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="相关字段:" size="mini" prop="fieldName">
                <el-input v-model.trim="formData.fieldName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="相关字段值:" size="mini" prop="fieldValue">
                <el-select v-model="formData.fieldValue" size="mini" placeholder="请选择相关字段值" style="width:100%">
                  <el-option v-for="item in fieldValueList" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="提醒角色:" size="mini" prop="remindRoleArr">
                <el-select v-model="formData.remindRoleArr" multiple size="mini" placeholder="提醒角色" style="width:100%" @change="changeRole">
                  <el-option v-for="item in remindRoleList" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
                </el-select>
                <!-- <c-dict-select v-model="formData.remindRoleArr" dict-type-code="REMIND_ROLE" multiple placeholder="提醒角色" style="width:100%" @change="changeRole" /> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="提醒方式:" size="mini" prop="remindTypeArr">
                <c-dict-select v-model="formData.remindTypeArr" dict-type-code="REMIND_TYPE" multiple placeholder="提醒方式" style="width:100%" @change="changeMode" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="执行规则:" size="mini" prop="executeRule">
                <c-dict-select v-model="formData.executeRule" dict-type-code="EXECUTE_RULE" placeholder="执行规则" style="width:100%" />
              </el-form-item>
            </el-col>
            <el-col v-if="formData.executeRule === 'B'" :span="12">
              <el-form-item label="执行任务规则:" size="mini" prop="cronJobRule" :rules="[{ required: formData.executeRule === 'B', message: '请选择执行定时方式' }]">
                <c-dict-select v-model="formData.cronJobRule" dict-type-code="CRON_JOB_RULE" placeholder="执行任务规则" style="width:100%" />
              </el-form-item>
            </el-col>
            <!-- </el-row>
          <el-row> -->
            <el-col v-if="formData.executeRule === 'B'" :span="12">
              <el-form-item label="定时任务字段" size="mini" prop="cronJobFiled" :rules="[{ required: formData.executeRule === 'B', message: '请选择定时任务字段' }]">
                <c-dict-select v-model="formData.cronJobFiled" dict-type-code="CRON_JOB_FILED" placeholder="定时任务字段" style="width:100%" />
              </el-form-item>
            </el-col>
            <el-col v-if="formData.executeRule === 'B'" :span="12">
              <el-form-item
                label="定时任务开始天数"
                size="mini"
                prop="cronJobDay"
                :rules="[{ required: formData.executeRule === 'B', message: '请输入定时任务开始天数' },
                         { validator: validateTime, message: '请输入正整数' }]"
              >
                <el-input v-model.number="formData.cronJobDay" placeholder="请输入定时任务开始天数" />
              </el-form-item>
            </el-col>
            <!-- </el-row>
          <el-row> -->
            <el-col :span="12">
              <el-form-item label="消息中心模板编码:" size="mini" prop="mcenterCode">
                <el-input v-model.number="formData.mcenterCode" placeholder="请输入消息中心模板编码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="消息内容:" size="mini" prop="contents">
                <el-input v-model.number="formData.contents" type="textarea" placeholder="请输入消息内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer">
        <el-button size="mini" @click="handleBack">取消</el-button>
        <el-button type="primary" size="mini" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDictByPatchType } from '@/api/dataDict'
import { saveMessageTemplate, getMessageTemplate } from '@/api/basicData'
// import { getUserInfo } from '@/utils/auth'
// import fileUploader from '@/components/importFile'
// import { postConfigAttachmentTemplate, changeFileList } from '@/api/proConfig'
// import { getShopAttachment } from '@/api/decorate'
export default {
  name: 'EidtDialog',
  // components: { fileUploader },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    const validateDay = (rule, value, callback) => {
      const reg = /^[1-9][0-9]?$/
      if (value && !reg.test(value)) {
        return callback(new Error('请输入数字不能以0开头，且不能大于99'))
      } else if (isNaN(Number(value)) || Number(value) <= 0 || value > 99) {
        return callback(new Error('请输入1到99的正整数'))
      } else if (value === '' || value === null || value === undefined) {
        console.log('value', value)
        return callback(new Error('请输入定时任务开始天数'))
      }
      callback()
    }
    return {
      surveyStateList: [],
      designScheduleList: [],
      decorationStepsList: [],
      negotiationList: [], // 洽谈进度
      designStateList: [],
      taskStateList: [],
      reminderModeList: [],
      reminderRoleList: [],
      // performTasksList: [],
      // currentTimeList: [],
      fieldValueList: [],
      remindRoleList: [],
      formData: {
        remindTypeArr: [],
        remindRoleArr: []
      },
      validateTime: validateDay,
      formRules: {
        configName: [{ required: true, message: '请输入名称' }],
        belongProcess: [{ required: true, message: '请选择对应流程' }],
        fieldValue: [{ required: true, message: '请选择相关字段值' }],
        remindRoleArr: [{ required: true, message: '请选择提醒角色' }],
        remindTypeArr: [{ required: true, message: '请选择提醒方式' }],
        executeRule: [{ required: true, message: '请选择执行规则' }],
        mcenterCode: [{ required: true, message: '请输入消息中心模板编码' }],
        contents: [{ required: true, message: '请输入消息内容' }]
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  async created() {
    this.$nextTick(() => {
      this.$refs.refForm.clearValidate()
    })
    await this.getDictByPatchTypeAll(['SHOP_SURVEY_STATE', 'PIC_DESIGN_SCHEDULE',
      'SHOP_DECORATION_STEPS', 'SHOP_DESIGN_STATE', 'DESIGN_TASK_STATE',
      'REMIND_TYPE', 'REMIND_ROLE', 'CRON_JOB_FILED', 'CRON_JOB_RULE', 'NEGOTIATION']).then(res => {
      this.surveyStateList = res.SHOP_SURVEY_STATE // 测绘进度
      this.designScheduleList = res.PIC_DESIGN_SCHEDULE // 图纸设计进度
      this.decorationStepsList = res.SHOP_DECORATION_STEPS // 装修步骤
      this.designStateList = res.SHOP_DESIGN_STATE // 设计进度--设计流程
      this.taskStateList = res.DESIGN_TASK_STATE // 设计任务进度--设计任务
      this.negotiationList = res.NEGOTIATION// 洽谈进度
      this.reminderModeList = res.REMIND_TYPE // 提醒方式
      this.reminderRoleList = res.REMIND_ROLE // 提醒角色
      // this.performTasksList = res.CRON_JOB_FILED // 定时规则
      // this.currentTimeList = res.CRON_JOB_RULE // 当前时间
    })
    if (this.detailData.id) {
      getMessageTemplate(this.detailData.id).then(res => {
        if (res.success && res.data) {
          this.changeProcess(res.data.belongProcess)
          this.formData = res.data
          this.$set(this.formData, 'remindRoleArr', this.convertDataFormat(res.data.remindRole))
          this.$set(this.formData, 'remindTypeArr', this.convertDataFormat(res.data.remindType))
        }
      })
    }
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    convertDataFormat(str) {
      if (!str || !str.length) return
      const arr = str.split(',')
      return arr
    },
    changeProcess(value) {
      if (value === 'A') {
        this.formData.fieldName = '测绘进度'
        this.fieldValueList = this.surveyStateList
        this.remindRoleList = this.reminderRoleList.filter(item => item.dictCode === 'A')
      } else if (value === 'B') {
        this.formData.fieldName = '设计进度'
        this.fieldValueList = this.designStateList
        this.remindRoleList = this.reminderRoleList.filter(item => item.dictCode !== 'C')
      } else if (value === 'C') {
        this.formData.fieldName = '任务进度'
        this.fieldValueList = this.taskStateList
        this.remindRoleList = this.reminderRoleList.filter(item => item.dictCode === 'A')
      } else if (value === 'D') {
        this.formData.fieldName = '图纸设计进度'
        this.fieldValueList = this.designScheduleList
        this.remindRoleList = this.reminderRoleList
      } else if (value === 'E') {
        this.formData.fieldName = '装修步骤'
        this.fieldValueList = this.decorationStepsList
        this.remindRoleList = this.reminderRoleList.filter(item => item.dictCode !== 'C')
      } else if (value === 'H') {
        this.formData.fieldName = '洽谈进度'
        this.fieldValueList = this.negotiationList // 洽谈进度
        this.remindRoleList = this.reminderRoleList
      }
      this.$set(this.formData, 'remindRoleArr', [])
      this.$set(this.formData, 'remindRole', '')
      this.$set(this.formData, 'fieldValue', '')
      this.$nextTick(() => {
        this.$refs.refForm.clearValidate()
      })
    },
    // 选择提醒角色
    changeRole(data) {
      if (data && data.length) {
        this.formData.remindRole = this.formData.remindRoleArr.toString()
      }
    },
    // 选择提醒方式
    changeMode(data) {
      if (data && data.length) {
        this.formData.remindType = this.formData.remindTypeArr.toString()
      }
    },
    // 取消
    handleBack() {
      this.dialogShow = false
      this.clearForm()
    },
    // 清空表单
    clearForm(done) {
      this.formData = {
        staff: [],
        office: []
      }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 提交
    submitForm() {
      this.$refs.refForm.validate((valid) => {
        if (valid) {
          // console.log('提交', this.formData)
          // return
          saveMessageTemplate(this.formData).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.dialogShow = false
              this.clearForm()
              const isNew = !this.formData.id
              this.$emit('success', isNew)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
